﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Table = FCNS.Data.Table;
using System.Diagnostics;
using DoubleH.Utility;
using System.Collections.ObjectModel;
using DoubleH.Utility.Configuration;

namespace PurchaseOrderS
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            InitEvent();
        }

        Table.PurchaseOrderS order = null;
        DataTableText tableText = DataTableText.采购单据商品编辑;

        public void Init(Table.PurchaseOrderS.EnumFlag flag, Table.PurchaseOrderS obj)
        {
            buttonCopyXJ.IsEnabled = false;
            order = obj ?? new Table.PurchaseOrderS(flag);
            InitVar();

            productSListInfoObject.Init(DoubleHConfig.UserConfig.GetUserUIparams(tableText));
            productSListInfoObject.ShowAverage = false;
            corSelect1.Init(false);
            userSelect1.Init(Table.UserS.EnumFlag.经办人);
            uCUniqueSInvoice.Init(Table.UniqueS.EnumFlag.发票定义);

            InitOrder();
        }

        private void InitOrder()
        {
            Debug.Assert(order != null);

            bool b = (order.Enable == Table.PurchaseOrderS.EnumEnable.入账 || order.Enable == Table.PurchaseOrderS.EnumEnable.作废);
            dateTimeUpDownKaiDan.IsReadOnly = b;
            dateTimeUpDownDaoHuo.IsReadOnly = b;
            corSelect1.IsEnabled = !b;
            userSelect1.IsReadOnly = b;
            textBoxNote.IsReadOnly = b;

            uCStoreS1.IsEnabled = !b;
            checkBoxDefault.IsEnabled = !b;
            buttonZuoFei.IsEnabled = !b;
            buttonSave.IsEnabled = !b;
            buttonShenHe.IsEnabled = !b;
            uCUniqueSInvoice.IsEnabled = !b;
            if (order.Flag == Table.PurchaseOrderS.EnumFlag.采购订单)
                doubleUpDownAdvance.IsEnabled = !b;
            else
                doubleUpDownAdvance.IsEnabled = false;


            dateTimeUpDownKaiDan.Value = order.OrderDateTime;
            dateTimeUpDownDaoHuo.Value = order.ArrivalDateTime;
            label1OrderNo.Content = order.OrderNO;
            corSelect1.SelectedObjectId = order.CorSId;
            userSelect1.SelectedValue = order.OperatorerSId;
            uCStoreS1.SelectedObjectId = order.StoreSId;
            textBoxStoreAddress.Text = order.Address;
            textBoxNote.Text = order.Note;
            uCUniqueSInvoice.SelectedObjectId = order.InvoiceType;
            doubleUpDownAdvance.Value = order.Advance;

            productSListInfoObject.ItemsSource = order.ProductSList;
            productSListInfoObject.IsReadOnly = false;
           if( order.Flag == Table.PurchaseOrderS.EnumFlag.采购退货单)
           {
                productSListInfoObject.MustHasStoreS  =true;
                productSListInfoObject.ProductSType = ProductS.GetProductS.EnumProductS.库存调价单商品;
           }
           else
           {
                productSListInfoObject.MustHasStoreS = false;
                productSListInfoObject.ProductSType = ProductS.GetProductS.EnumProductS.可采购商品;
           }

            if (order.Id == -1)
                productSListInfoObject.EnableText = string.Empty;
            else
            {
                switch (order.Enable)
                {
                    case Table.PurchaseOrderS.EnumEnable.审核:
                    case Table.PurchaseOrderS.EnumEnable.入账:
                    case Table.PurchaseOrderS.EnumEnable.作废:
                    case Table.PurchaseOrderS.EnumEnable.预付款:
                        productSListInfoObject.EnableText = order.Enable.ToString();
                        productSListInfoObject.IsReadOnly = true;
                        break;
                    default:
                        productSListInfoObject.EnableText = order.Id == -1 ? string.Empty : order.Enable.ToString();
                        break;
                }
            }

        }

        private void InitVar()
        {
            switch (order.Flag)
            {
                //case Table.PurchaseOrderS.EnumFlag.采购询价单:
                //    tableText = DataTableText.销售询价单商品编辑;
                //    productSListInfoObject.ShowAverage = true;
                //    productSListInfoObject.CanNegativeSales = true;
                //    buttonNew.Content = "询价单（新）";
                //    break;
                case Table.PurchaseOrderS.EnumFlag.采购退货单:
                    labelDate.Content = "退货日期";
                    productSListInfoObject.Foreground = Brushes.Red;
                    buttonNew.Content = "退货单（新）";
                    uCUniqueSInvoice.IsEnabled = false;
                    doubleUpDownAdvance.IsEnabled = false;
                    break;

                case Table.PurchaseOrderS.EnumFlag.赠品入库单:
                    tableText = DataTableText.赠品商品编辑;
                    expanderNew.IsEnabled = false;
                    break;

                case Table.PurchaseOrderS.EnumFlag.采购订单:
                    buttonNew.Content = "采购单（新）";
                    break;
            }

            string name = order.Flag.ToString();
            this.Title = name;
            labelTitle.Content = name;
        }

        private void InitEvent()
        {
            uCStoreS1.SelectedObjectEvent += (ee) => ChangedStoreS(ee);
            this.Closing += (ss, ee) => ee.Cancel = !DataSaveOrCancel();
            corSelect1.CorSChanged += (ee) => order.CorSId = corSelect1.SelectedObjectId;
            buttonPre.Click += (ss, ee) => OrderPre();
            buttonNext.Click += (ss, ee) => OrderNext();
            doubleUpDownDefault.ValueChanged += (ss, ee) => ChangeQuantity();
            checkBoxDefault.Checked += (ss, ee) => ChangeQuantity();
            buttonZuoFei.Click += (ss, ee) => OrderZuoFei();
            buttonSave.Click += (ss, ee) => OrderSave();
            buttonShenHe.Click += (ss, ee) => OrderShenHe();
            buttonPrint.Click += (ss, ee) => PrintFunction.Print(order, DataTableText.采购订单);

            buttonNew.Click += (ss, ee) =>
            {
                OrderNew();
                expanderNew.IsExpanded = false;
            };
            buttonCopyXJ.Click += (ss, ee) =>
            {
                if (order.Id == -1)
                    return;

                order = (Table.PurchaseOrderS)order.CloneObject(new object[] { Table.PurchaseOrderS.EnumFlag.采购询价单 });
                OrderCopy();
            };
            buttonCopyPF.Click += (ss, ee) =>
            {
                if (order.Id == -1)
                    return;

                order = (Table.PurchaseOrderS)order.CloneObject(new object[] { Table.PurchaseOrderS.EnumFlag.采购订单 });
                OrderCopy();
            };
            buttonCopyTH.Click += (ss, ee) =>
            {
                if (order.Id == -1)
                    return;

                order = (Table.PurchaseOrderS)order.CloneObject(new object[] { Table.PurchaseOrderS.EnumFlag.采购退货单 });
                OrderCopy();
            };
            expanderNew.MouseLeave += (ss, ee) => expanderNew.IsExpanded = false;
        }

        private void ChangedStoreS(Table.StoreS ee)
        {
            if (order.Flag == Table.PurchaseOrderS.EnumFlag.采购退货单)
                productSListInfoObject.StoreS = ee;

            textBoxStoreAddress.Text = ee.Address;
        }

        private void ChangeQuantity()
        {
            if (checkBoxDefault.IsChecked == true)
                productSListInfoObject.ResetAllProductQuantity((double)doubleUpDownDefault.Value);
        }

        private void OrderPre()
        {
            Table.PurchaseOrderS p = Table.PurchaseOrderS.GetPreObject(order.Id, order.Flag);
            if (p == null)
                MessageWindow.Show("没有上一条记录了");
            else
            {
                order = p;
                InitOrder();
            }
        }

        private void OrderNext()
        {
            FCNS.Data.Table.PurchaseOrderS p = Table.PurchaseOrderS.GetNextObject(order.Id, order.Flag);

            if (p == null)
                MessageWindow.Show("没有下一条记录了");
            else
            {
                order = p;
                InitOrder();
            }
        }

        private void OrderNew()
        {
            if (DataSaveOrCancel())
            {
                order = new FCNS.Data.Table.PurchaseOrderS(order.Flag);
                InitOrder();
            }
        }

        private void OrderZuoFei()
        {
            //如果订单还没有保存到数据库就没必要删除了,免去控件的刷新
            if (order.Id == -1)
                return;

            if (MessageWindow.Show("", "确定要作废此单据吗?", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
            {
                Table.DataTableS.EnumDatabaseStatus result = order.ZuoFei();
                MessageWindow.Show(result.ToString());
                if (result == Table.DataTableS.EnumDatabaseStatus.操作成功)
                    OrderNew();
            }
        }

        private void OrderSave()
        {
            order.OrderDateTime = (DateTime)dateTimeUpDownKaiDan.Value;
            order.ArrivalDateTime = (DateTime)dateTimeUpDownDaoHuo.Value;
            if (!string.IsNullOrEmpty(userSelect1.Text))
                order.OperatorerSId = (Int64)userSelect1.SelectedValue;

            order.StoreSId = uCStoreS1.SelectedObjectId;
            order.Address = textBoxStoreAddress.Text;
            order.Note = textBoxNote.Text;
            order.Advance = doubleUpDownAdvance.Value.Value;
            order.InvoiceType = uCUniqueSInvoice.SelectedObjectId;

            Table.DataTableS.EnumDatabaseStatus result;
            if (order.Id == -1)
                result = order.Insert();
            else
                result = order.Update();

            if (result == Table.DataTableS.EnumDatabaseStatus.操作成功)
                InitOrder();
            else
                MessageWindow.Show(result.ToString());
        }

        private void OrderShenHe()
        {
            if (order.Id == -1)
            {
                MessageWindow.Show("请先保存单据");
                return;
            }

            order.AuditorUserSId = Table.UserS.LoginUser.Id;
            Table.DataTableS.EnumDatabaseStatus result = order.ShenHe();
            if (result == Table.DataTableS.EnumDatabaseStatus.操作成功)
                InitOrder();
            else
                MessageWindow.Show(result.ToString());
        }

        private bool DataSaveOrCancel()
        {
            if (string.IsNullOrEmpty(label1OrderNo.Content.ToString()) && productSListInfoObject.HasItems)
            {
                switch (MessageBox.Show("是否保存单据?", "", MessageBoxButton.YesNoCancel))
                {
                    case MessageBoxResult.Yes:
                        OrderSave();
                        break;
                    case MessageBoxResult.Cancel:
                        return false;
                }
            }
            return true;
        }

        private void OrderCopy()
        {
            InitVar();
            order.Enable = Table.PurchaseOrderS.EnumEnable.下单;
            order.Id = -1;
            InitOrder();
            label1OrderNo.Content = "";
            dateTimeUpDownKaiDan.Value = DateTime.Now;
            dateTimeUpDownDaoHuo.Value = DateTime.Now;
            expanderNew.IsExpanded = false;
        }
    }
}   